package com.yunatt.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yunatt.mapper.PersonMapper;
import com.yunatt.model.*;
import com.yunatt.model.vo.*;
import com.yunatt.service.*;
import com.yunatt.uitls.ImageProcess;
import com.yunatt.websocket.WSServer;
import com.yunatt.websocket.WebSocketPool;
import org.java_websocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/api")
public class DemoController {

    @Autowired
    private PersonMapper personMapper;
    @Autowired
    private PersonService personService;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private EnrollInfoService enrollInfoService;
    @Autowired
    private MachineCommandService machineComandService;
    @Autowired
    private AccessDayService accessDayService;
    @Autowired
    private AccessWeekService accessWeekService;
    @Autowired
    private RecordsService recordService;

    @Autowired
    private ImageProcess imageProcess;

    @Value("${filepath}")
    private  String filepath;
    @Autowired
    private WSServer wsServer;

    /**
     * 从数据库中获取所有人
     * @param pageNum
     * @param limit
     * @param vl
     * @return
     */
    @RequestMapping(value = "/emps")
    @ResponseBody
    public Map getAllPersonFromDB(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,@RequestParam(value = "limit", defaultValue = "1") Integer limit,  @RequestParam(value = "name", defaultValue = "") String vl){

        PageHelper.startPage(pageNum, limit);
        List<PersonEntity> list = personMapper.selectByName(vl);
        PageInfo page = new PageInfo(list);
        List<UserInfo> emps = new ArrayList<UserInfo>();
        for (PersonEntity personEntity : list) {
            UserInfo userInfo = new UserInfo();
            userInfo.setEnrollId(personEntity.getId());
            userInfo.setAdmin(personEntity.getRollId());
            userInfo.setName(personEntity.getName());
            EnrollInfoEntity enrollInfo= personMapper.selectEnrollById(personEntity.getId());
            if (enrollInfo!=null){
                userInfo.setImagePath(enrollInfo.getImagePath());
            }
            List<RecordsEntity> recordsEntities = recordService.selectUserRecords(personEntity.getId());
            userInfo.setRecordsEntityList(recordsEntities);
            emps.add(userInfo);

        }
        Map<String,Object>map =new HashMap<>();
        map.put("count",page.getTotal());
        map.put("data",emps);
        map.put("code",0);
        map.put("msg","success");
        return map;

    }

    /**
     * 从设备中删除人员
     * @param enrollId
     * @param deviceSn
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/deletePersonFromDevice", method = RequestMethod.GET)
    public Map deleteDeviceUserInfo(@RequestParam("enrollId") Long enrollId,
                                    @RequestParam("deviceSn") String deviceSn) {
        System.out.println("Delete User devicesn===================" + deviceSn);
        personService.deleteUserInfoFromDevice(enrollId,deviceSn);
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;
    }

    /** 显示所有的打卡记录 */
    @RequestMapping(value = "/records")
    @ResponseBody
    public Map getAllLogFromDB(@RequestParam(value = "page", defaultValue = "1") Integer pageNum,@RequestParam(value = "limit", defaultValue = "1") Integer limit,  @RequestParam(value = "deviceSn", defaultValue = "") String deviceSn) {


        PageHelper.startPage(pageNum, limit);
        List<RecordsEntity> records = recordService.selectAllRecords();
        PageInfo page = new PageInfo(records);
        Map<String,Object>map =new HashMap<>();
        map.put("count",page.getTotal());
        map.put("data",records);
        map.put("code",0);
        map.put("msg","success");
        return map;

    }

    /**
     * 从数据库里获取所有设备
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/device", method = RequestMethod.GET)
    public Map getAllDevice() {
        List<DeviceEntity> deviceList = deviceService.findAllDevice();
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("data",deviceList);
        map.put("msg","success");
        return map;
    }

    /**
     * 添加人员
     * @param personTemp
     * @param pic
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "addPerson", method = RequestMethod.POST)
    public Map addPerson(PersonTemp personTemp, MultipartFile pic, HttpServletRequest httpServletRequest,
                         HttpServletResponse httpServletResponse) throws Exception {
        String path = filepath;
        System.out.println("Real path of image" + path);
        System.out.println("Add personnel information===================" + personTemp);
        String photoName = "";
        String newName = "";
        // EnrollInfo enrollInfo=new EnrollInfo();
        if (pic != null) {
            if (pic.getOriginalFilename() != null && !("").equals(pic.getOriginalFilename())) {
//                photoName = pic.getOriginalFilename();
                newName = UUID.randomUUID().toString();
//                newName = UUID.randomUUID().toString() + photoName.substring(photoName.lastIndexOf("."));
//                File photoFile = new File(path + newName);
                String base = Base64.getEncoder().encodeToString(pic.getBytes());
                imageProcess.base64toImage(base,newName);
//                if (!photoFile.exists()) {
//                    photoFile.mkdirs();
//                }
//                pic.transferTo(photoFile);

            }

        }
        PersonEntity person = new PersonEntity();
        person.setId(personTemp.getUserId());
        person.setName(personTemp.getName());
        person.setRollId(personTemp.getPrivilege());
        PersonEntity person2 = personService.selectByPrimaryKey(personTemp.getUserId());
        if (person2 == null) {
            personService.insert(person);
        }
        if (personTemp.getPassword() != null && !personTemp.getPassword().equals("")) {
            EnrollInfoEntity enrollInfoTemp2 = new EnrollInfoEntity();
            enrollInfoTemp2.setBackupnum(10);
            enrollInfoTemp2.setEnrollId(personTemp.getUserId());
            enrollInfoTemp2.setSignatures(personTemp.getPassword());
            enrollInfoService.insertSelective(enrollInfoTemp2);
        }
        if (personTemp.getCardNum() != null && !personTemp.getCardNum().equals("")) {
            EnrollInfoEntity enrollInfoTemp3 = new EnrollInfoEntity();
            enrollInfoTemp3.setBackupnum(11);
            enrollInfoTemp3.setEnrollId(personTemp.getUserId());
            enrollInfoTemp3.setSignatures(personTemp.getCardNum());
            enrollInfoService.insertSelective(enrollInfoTemp3);
        }

        if (newName != null && !newName.equals("")) {
            EnrollInfoEntity enrollInfoTemp = new EnrollInfoEntity();
            enrollInfoTemp.setBackupnum(50);
            enrollInfoTemp.setEnrollId(personTemp.getUserId());
            String base64Str = ImageProcess.imageToBase64Str(filepath + newName+".jpg");
            enrollInfoTemp.setImagePath(newName+".jpg");
            enrollInfoTemp.setSignatures(base64Str);
            System.out.println("Image data length" + base64Str.length());
            enrollInfoService.insertSelective(enrollInfoTemp);
        }
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;

    }


    /** 采集所有的用户 */
    @ResponseBody
    @RequestMapping(value = "/sendWs", method = RequestMethod.GET)
    public Map sendWs(@RequestParam("deviceSn") String deviceSn) {
        String message = "{\"cmd\":\"getuserlist\",\"stn\":true}";


        // WebSocketPool.sendMessageToDeviceStatus(deviceSn, message);
        List<DeviceEntity> deviceList = deviceService.findAllDevice();
        for (int i = 0; i < deviceList.size(); i++) {
            MachineCommandEntity machineCommand = new MachineCommandEntity();
            machineCommand.setContent(message);
            machineCommand.setName("getuserlist");
            machineCommand.setStatus(0);
            machineCommand.setSendStatus(0);
            machineCommand.setErrCount(0);
            machineCommand.setSerial(deviceList.get(i).getSerialNum());
            machineCommand.setGmtCrate(new Date());
            machineCommand.setGmtModified(new Date());
            machineCommand.setContent(message);
            machineComandService.addMachineCommand(machineCommand);
        }

        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;
    }

    /**
     * 功能未知1
     * @param deviceSn
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getUserInfo", method = RequestMethod.GET)
    public Map getUserInfo(@RequestParam("deviceSn") String deviceSn) {
        List<PersonEntity> person = new ArrayList<>();
        try {
            person = personService.selectAll();
        }catch (Exception e){
            e.printStackTrace();
        }

        List<EnrollInfoEntity> enrollsPrepared = new ArrayList<EnrollInfoEntity>();
        for (int i = 0; i < person.size(); i++) {
            Long enrollId2 = person.get(i).getId();
            List<EnrollInfoEntity> enrollInfos = enrollInfoService.selectByEnrollId(enrollId2);
            for (int j = 0; j < enrollInfos.size(); j++) {
                if (enrollInfos.get(j).getEnrollId() != null && enrollInfos.get(j).getBackupnum() != null) {
                    enrollsPrepared.add(enrollInfos.get(j));
                }
            }
        }
        System.out.println("Collect user data" + enrollsPrepared);
        personService.getSignature2(enrollsPrepared, deviceSn);

        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;
    }

    /***
     * 指定SN获取考勤机用户信息
     * @param deviceSn
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getUserListByDeviceSn", method = RequestMethod.GET)
    public void getUserListByDeviceSn(@RequestParam("deviceSn") String deviceSn) {
        String message = "{\"cmd\":\"getuserlist\",\"stn\":true}";

    }
    /**
     * 获取全部考勤机用户信息
     * @param deviceSn
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getUserListByDeviceSnAll", method = RequestMethod.GET)
    public void getUserListByDeviceSnAll(@RequestParam("deviceSn") String deviceSn) {
        String message = "{\"cmd\":\"getuserlist\",\"stn\":true}";
        WebSocketPool.sendMessageToDeviceStatus(deviceSn, message);
    }
    /** 下发所有用户，面向选中考勤机 */
    @ResponseBody
    @RequestMapping(value = "/setPersonToDevice", method = RequestMethod.GET)
    public Map sendSetUserInfo(@RequestParam("deviceSn") String deviceSn) {

        personService.setUserToDevice2(deviceSn);
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;

    }

    /**
     * 从device设置用户名
     * @param deviceSn
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "setUsernameToDevice", method = RequestMethod.GET)
    public Map setUsernameToDevice(@RequestParam("deviceSn") String deviceSn) {
        personService.setUsernameToDevice(deviceSn);
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;
    }

    /** 初始化考勤机 */
    @ResponseBody
    @RequestMapping(value = "/initSystem", method = RequestMethod.GET)
    public Map initSystem(@RequestParam("deviceSn") String deviceSn) {
        System.out.println("initialization request");
        String message = "{\"cmd\":\"enabledevice\"}";
        String message2 = "{\"cmd\":\"settime\",\"cloudtime\":\"2020-12-23 13:49:30\"}";
        String s4 = "{\"cmd\":\"settime\",\"cloudtime\":\"2016-03-25 13:49:30\"}";
        String s2 = "{\"cmd\":\"setdevinfo\",\"deviceid\":1,\"language\":0,\"volume\":0,\"screensaver\":0,\"verifymode\":0,\"sleep\":0,\"userfpnum\":3,\"loghint\":1000,\"reverifytime\":0}";
        String s3 = "{\"cmd\":\"setdevlock\",\"opendelay\":5,\"doorsensor\":0,\"alarmdelay\":0,\"threat\":0,\"InputAlarm\":0,\"antpass\":0,\"interlock\":0,\"mutiopen\":0,\"tryalarm\":0,\"tamper\":0,\"wgformat\":0,\"wgoutput\":0,\"cardoutput\":0,\"dayzone\":[{\"day\":[{\"section\":\"01:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"}]},{\"day\":[{\"section\":\"02:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"}]},{\"day\":[{\"section\":\"03:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"}]},{\"day\":[{\"section\":\"04:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"}]},{\"day\":[{\"section\":\"05:00~00:0\n"
                + "0\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"}]},{\"day\":[{\"section\":\"06:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"}]},{\"day\":[{\"section\":\"07:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"}]},{\"day\":[{\"section\":\"08:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"},{\"section\":\"00:00~00:00\"}]}],\"weekzone\":[{\"week\":[{\"day\":0},{\"day\":1},{\"day\":2},{\"day\":3},{\"day\":4},{\"day\":5},{\"day\":6}]},{\"week\":[{\"day\":10},{\"day\":11},{\"day\":12},{\"day\":13},{\"day\":14},{\"day\":15},{\"day\":16}]},{\"week\":[{\"day\":20},{\"day\":21},{\"day\":22},{\"day\":23},{\"day\":24},{\"day\":25},{\"day\":26}]},\n"
                + "{\"week\":[{\"day\":30},{\"day\":31},{\"day\":32},{\"day\":33},{\"day\":34},{\"day\":35},{\"day\":36}]},{\"week\":[{\"day\":40},{\"day\":41},{\"day\":42},{\"day\":43},{\"day\":44},{\"day\":45},{\"day\":46}]},{\"week\":[{\"day\":50},{\"day\":51},{\"day\":52},{\"day\":53},{\"day\":54},{\"day\":55},{\"day\":56}]},{\"week\":[{\"day\":60},{\"day\":61},{\"day\":62},{\"day\":63},{\"day\":64},{\"day\":65},{\"day\":66}]},{\"week\":[{\"day\":70},{\"day\":71},{\"day\":72},{\"day\":73},{\"day\":74},{\"day\":75},{\"day\":76}]}],\"lockgroup\":[{\"group\":0},{\"group\":1},{\"group\":2},{\"group\":3},{\"group\":4}],\"nopentime\":[{\"day\":0},{\"day\":0},{\"day\":0},{\"day\":0},{\"day\":0},{\"day\":0},{\"day\":0}]}\n"
                + "";

        String messageTemp = "{\"cmd\":\"setuserlock\",\"count\":1,\"record\":[{\"enrollid\":1,\"weekzone\":1,\"weekzone2\":3,\"group\":1,\"starttime\":\"2010-11-11 00:00:00\",\"endtime\":\"2030-11-11 00:00:00\"}]}";
        String s5 = "{\"cmd\":\"enableuser\",\"enrollid\":1,\"enflag\":0}";
        String s6 = "{\"cmd\":\"getusername\",\"enrollid\":1}";
        String message22 = "{\"cmd\":\"initsys\"}";

        MachineCommandEntity machineCommand = new MachineCommandEntity();
        machineCommand.setContent(message22);
        machineCommand.setName("initsys");
        machineCommand.setStatus(0);
        machineCommand.setErrCount(0);
        machineCommand.setSendStatus(0);
        machineCommand.setSerial(deviceSn);
        machineCommand.setGmtCrate(new Date());
        machineCommand.setGmtModified(new Date());

        machineComandService.addMachineCommand(machineCommand);

        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;
    }

    /** 设置周时间段 */
    @RequestMapping(value = "/accessDays", method = RequestMethod.GET)
    @ResponseBody
    public Map getAccessDayFromDB() {
        List<AccessDayEntity> accessDays = accessDayService.selectAll();
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        map.put("accessdays",accessDays);
        return map;
    }

    /** 添加天时段,面向全部考勤机 */
    @ResponseBody
    @RequestMapping(value = "/setAccessDay", method = RequestMethod.POST)
    public Map setAccessDay( AccessDayEntity accessDay) {
        if (accessDayService.selectByPrimaryKey(accessDay.getId()) != null) {
            accessDayService.updateByPrimaryKey(accessDay);

        }else {
            accessDayService.insert(accessDay);
        }
        accessDayService.setAccessDay();
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;
    }


    /** 添加周时段，面向全部考勤机 */
    @ResponseBody
    @RequestMapping(value = "/setAccessWeek", method = RequestMethod.POST)
    public Map setAccessWeek(@ModelAttribute AccessWeekEntity accessWeek) {
        Map<String,Object>map =new HashMap<>();
        if (accessWeekService.selectByPrimaryKey(accessWeek.getId()) != null) {
            accessWeekService.updateByPrimaryKey(accessWeek);
            map.put("code",0);
            map.put("msg","success");
            return map;
        }else {
            accessWeekService.insert(accessWeek);

        }
        accessWeekService.setAccessWeek();
        map.put("code",0);
        map.put("msg","success");
        return map;

    }

    /** 设置锁组合 */
    @ResponseBody
    @RequestMapping(value = "/setLocckGroup", method = RequestMethod.POST)
    public Map setLockGroup(@ModelAttribute LockGroup lockGroup) {
        deviceService.setLockGroup(lockGroup);
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;
    }
    @ResponseBody
    @RequestMapping(value = "/getDeviceInfo", method = RequestMethod.GET)
    public Map getDeviceInfo(@RequestParam("deviceSn") String deviceSn) {
        String message = "{\"cmd\":\"getdevinfo\"}";

        MachineCommandEntity machineCommand = new MachineCommandEntity();
        machineCommand.setContent(message);
        machineCommand.setName("getdevinfo");
        machineCommand.setStatus(0);
        machineCommand.setSendStatus(0);
        machineCommand.setErrCount(0);
        machineCommand.setSerial(deviceSn);
        machineCommand.setGmtCrate(new Date());
        machineCommand.setGmtModified(new Date());

        machineComandService.addMachineCommand(machineCommand);
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;
    }

    /**
     * 开门
     * @param doorNum
     * @param deviceSn
     * @return
     */
    @RequestMapping(value = "/openDoor", method = RequestMethod.GET)
    @ResponseBody
    public Map openDoor(@RequestParam("doorNum") int doorNum, @RequestParam("deviceSn") String deviceSn) {
        String message = "{\"cmd\":\"opendoor\"" + ",\"doornum\":" + doorNum + "}";

        MachineCommandEntity machineCommand = new MachineCommandEntity();
        machineCommand.setContent(message);
        machineCommand.setName("opendoor");
        machineCommand.setStatus(0);
        machineCommand.setSendStatus(0);
        machineCommand.setErrCount(0);
        machineCommand.setSerial(deviceSn);
        machineCommand.setGmtCrate(new Date());
        machineCommand.setGmtModified(new Date());

        machineComandService.addMachineCommand(machineCommand);
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;
    }

    /**
     * 获取dev锁
     * @param deviceSn
     * @return
     */
    @RequestMapping(value = "/getDevLock", method = RequestMethod.GET)
    @ResponseBody
    public Map getDevLock(@RequestParam("deviceSn") String deviceSn) {
        String message = "{\"cmd\":\"getdevlock\"}";

        MachineCommandEntity machineCommand = new MachineCommandEntity();
        machineCommand.setContent(message);
        machineCommand.setName("getdevlock");
        machineCommand.setStatus(0);
        machineCommand.setSendStatus(0);
        machineCommand.setErrCount(0);
        machineCommand.setSerial(deviceSn);
        machineCommand.setGmtCrate(new Date());
        machineCommand.setGmtModified(new Date());

        machineComandService.addMachineCommand(machineCommand);
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;

    }
    /** 获取单个用户 */
    @ResponseBody
    @RequestMapping("sendGetUserInfo")
    public Map sendGetUserInfo(@RequestParam("enrollId") int enrollId, @RequestParam("backupNum") int backupNum,
                               @RequestParam("deviceSn") String deviceSn) {

        List<DeviceEntity> deviceList = deviceService.findAllDevice();
        System.out.println("设备信息" + deviceList);

        String message = "{\"cmd\":\"getuserinfo\",\"enrollid\":" + enrollId + ",\"backupnum\":" + backupNum + "}";

        machineComandService.addGetOneUserCommand(enrollId, backupNum, deviceSn);

        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;
    }
    /** 下发单个用户到机器，对选中考勤机 */
    @ResponseBody
    @RequestMapping(value = "/setOneUser", method = RequestMethod.GET)
    public Map setOneUserTo(@RequestParam("enrollId") Long enrollId, @RequestParam("backupNum") int backupNum,
                            @RequestParam("deviceSn") String deviceSn) {
        Map<String,Object>map =new HashMap<>();

        PersonEntity person = personService.selectByPrimaryKey(enrollId);
        EnrollInfoEntity enrollInfo = enrollInfoService.selectByBackupnum(enrollId, backupNum);
        if (enrollInfo != null) {
            personService.setUserToDevice(enrollId, person.getName(), backupNum, person.getRollId(),
                    enrollInfo.getSignatures(), deviceSn);
            map.put("code",0);
            map.put("msg","success");
            return map;
        } else if (backupNum == -1) {
            personService.setUserToDevice(enrollId, person.getName(), backupNum, 0, "", deviceSn);
            map.put("code",0);
            map.put("msg","success");
            return map;
        } else {
            map.put("code",1);
            map.put("msg","error");
            return map;
        }

    }
    /** 设置用户锁权限 */
    @ResponseBody
    @RequestMapping(value = "/setUserLock", method = RequestMethod.POST)
    public Map setUserLock(@ModelAttribute UserLock userLock) {

        deviceService.setUserLock(userLock, userLock.getStarttime(), userLock.getEndtime());
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;
    }

    /**
     * 获取用户锁
     * @param enrollId
     * @param deviceSn
     * @return
     */
    @RequestMapping(value = "/geUserLock", method = RequestMethod.GET)
    @ResponseBody
    public Map getUserLock(@RequestParam("enrollId") Integer enrollId, @RequestParam("deviceSn") String deviceSn) {

        String message = "{\"cmd\":\"getuserlock\",\"enrollid\":" + enrollId + "}";
        MachineCommandEntity machineCommand = new MachineCommandEntity();
        machineCommand.setContent(message);
        machineCommand.setName("getuserlock");
        machineCommand.setStatus(0);
        machineCommand.setSendStatus(0);
        machineCommand.setErrCount(0);
        machineCommand.setSerial(deviceSn);
        machineCommand.setGmtCrate(new Date());
        machineCommand.setGmtModified(new Date());

        machineComandService.addMachineCommand(machineCommand);

        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;
    }

    /**
     * 清理admin
     * @param deviceSn
     * @return
     */
    @RequestMapping(value = "/cleanAdmin", method = RequestMethod.GET)
    @ResponseBody
    public Map cleanAdmin(@RequestParam("deviceSn") String deviceSn) {
        String message = "{\"cmd\":\"cleanadmin\"}";

        MachineCommandEntity machineCommand = new MachineCommandEntity();
        machineCommand.setContent(message);
        machineCommand.setName("cleanadmin");
        machineCommand.setStatus(0);
        machineCommand.setSendStatus(0);
        machineCommand.setErrCount(0);
        machineCommand.setSerial(deviceSn);
        machineCommand.setGmtCrate(new Date());
        machineCommand.setGmtModified(new Date());

        machineComandService.addMachineCommand(machineCommand);
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;

    }

    /**
     * 同步时间
     * @param deviceSn
     * @return
     */
    @RequestMapping(value = "/synchronizeTime", method = RequestMethod.GET)
    @ResponseBody
    public Map synchronizeTime(@RequestParam("deviceSn") String deviceSn) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String timeStr = sdf.format(new Date());
        String message = "{\"cmd\":\"settime\",\"cloudtime\":\"" + timeStr + "\"}";
        if (WebSocketPool.wsDevice.get(deviceSn) != null) {
            WebSocketPool.sendMessageToDeviceStatus(deviceSn, message);
            System.out.println("Send command to machine:" + message);
            Map<String,Object>map =new HashMap<>();
            map.put("code",0);
            map.put("msg","success");
            return map;
        }
        Map<String,Object>map =new HashMap<>();
        map.put("code",1);
        map.put("msg","error");
        return map;

    }

    /** 采集所有的考勤记录，面向所有机器 */
    @ResponseBody
    @RequestMapping(value = "/getAllLog", method = RequestMethod.GET)
    public Map getAllLog(@RequestParam("deviceSn") String deviceSn) {
        String message = "{\"cmd\":\"getalllog\",\"stn\":true}";
        // String
        // messageTemp="{\"cmd\":\"getalllog\",\"stn\":true,\"from\":\"2020-12-03\",\"to\":\"2020-12-30\"}";
        MachineCommandEntity machineCommand = new MachineCommandEntity();
        machineCommand.setContent(message);
        machineCommand.setName("getalllog");
        machineCommand.setStatus(0);
        machineCommand.setSendStatus(0);
        machineCommand.setErrCount(0);
        machineCommand.setSerial(deviceSn);
        machineCommand.setGmtCrate(new Date());
        machineCommand.setGmtModified(new Date());
        machineComandService.addMachineCommand(machineCommand);
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;

    }

    /** 采集所有的考勤记录，面向所有机器 */
    @ResponseBody
    @RequestMapping(value = "/getNewLog", method = RequestMethod.GET)
    public Map getNewLog(@RequestParam("deviceSn") String deviceSn) {
        String message = "{\"cmd\":\"getnewlog\",\"stn\":true}";
        // String
        // messageTemp="{\"cmd\":\"getalllog\",\"stn\":true,\"from\":\"2020-12-03\",\"to\":\"2020-12-30\"}";
        System.out.println(message);
        MachineCommandEntity machineCommand = new MachineCommandEntity();
        machineCommand.setContent(message);
        machineCommand.setName("getnewlog");
        machineCommand.setStatus(0);
        machineCommand.setSendStatus(0);
        machineCommand.setErrCount(0);
        machineCommand.setSerial(deviceSn);
        machineCommand.setGmtCrate(new Date());
        machineCommand.setGmtModified(new Date());
        machineComandService.addMachineCommand(machineCommand);
        Map<String,Object>map =new HashMap<>();
        map.put("code",0);
        map.put("msg","success");
        return map;

    }
}
